package com.cheyun.netsalev3.dataSource

import androidx.lifecycle.MutableLiveData
import androidx.paging.DataSource
import androidx.paging.PageKeyedDataSource
import com.cheyun.netsalev3.repository.BasePageRepository
import com.cheyun.netsalev3.utils.api.NetworkState

/**
 * 分页数据源
 */
class DataSourceFactory<T>(var listener: BasePageRepository<T>, var networkState: MutableLiveData<NetworkState>) : DataSource.Factory<Int, T>() {
    val sourceLiveData = MutableLiveData<DataSource<Int, T>>()
    override fun create(): DataSource<Int, T> {
        var data = StockDataSource()
//        var data = StockDataSource2(listener,networkState)
        sourceLiveData.postValue(data)
        return data
    }

    interface callbackListener<T> {
        fun loadInitial(params: PageKeyedDataSource.LoadInitialParams<Int>, callback: (data: MutableList<T>) -> Unit)
        fun loadAfter(params: PageKeyedDataSource.LoadParams<Int>, callback: PageKeyedDataSource.LoadCallback<Int, T>)
        fun loadBefore(params: PageKeyedDataSource.LoadParams<Int>, callback: PageKeyedDataSource.LoadCallback<Int, T>)
    }

    inner class StockDataSource : PageKeyedDataSource<Int, T>() {
        override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int, T>) {
            networkState.postValue(NetworkState.LOADING)
            var method: (data: MutableList<T>) -> Unit = {
                callback.onResult(it, null, 2)
                networkState.postValue(NetworkState.LOADED)
            }
            listener.loadInitial(params, method)

        }

        override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, T>) {
            listener.loadAfter(params, callback)
        }

        override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, T>) {
            if (params.key - 1 <= 0) {
                return
            }
            listener.loadBefore(params, callback)
        }
    }

}
